<template >
    <div v-title data-title="码神之路" style="width:65%;max-width: 80%">

        <el-form :inline="true" :model="formInline" class="demo-form-inline">
          <el-form-item label="名称" label-width="100">
            <el-input v-model="formInline.categoryName" placeholder="名称"></el-input>
          </el-form-item>
          
          <el-form-item>
            <el-button type="primary" @click="onSubmit">查询</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="openDialog(null, -1)">添加</el-button>
          </el-form-item>
          <el-form-item>
            <el-button type="danger" @click="deleteCategoryList()">删除</el-button>
          </el-form-item>
        </el-form>

        <el-table
            :data="categories"
            stripe="true"
            style="width: auto;"
            @selection-change="handleSelectionChange">>
        
            <el-table-column type="selection" width="55">
            </el-table-column>
            <el-table-column label="序号" width="50" type="index" >
            </el-table-column>
            <el-table-column label="名称" width="200">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <p>ID: {{scope.row.id}}</p>
                  <p>名称: {{scope.row.categoryName}}</p>
                  <p>内容: {{scope.row.description}}</p>
                  <div slot="reference" class="name-wrapper">
                     <a @click="view(scope.row.id)" class="me-article-title">{{scope.row.categoryName}}</a>
                  </div>
                </el-popover>
                
              </template>
            </el-table-column>
             
            <el-table-column label="时间" width="200">
              <template slot-scope="scope">
                <el-popover trigger="hover" placement="top">
                  <img :src="scope.row.avatar" style="width: 100px;height:100px;object-fit: cover;"/>
                  <div slot="reference" class="name-wrapper">
                     图片
                  </div>
                </el-popover>
              </template>
            </el-table-column>
           
            <el-table-column label="操作" >
              <template slot-scope="scope">
                    <el-button
                        size="mini"
                        type="primary"
                        @click="openDialog(scope.row)"
                        >
                        修改</el-button>
                    <el-button
                    size="mini"
                    type="danger"
                    @click="handleDelete(scope.row)">删除</el-button>
              </template>

            </el-table-column>
        </el-table>

        <el-dialog title="编辑类型" :visible.sync="dialogFormVisible">
          <el-form :model="form">
            <el-form-item label="类型名称" :label-width="formLabelWidth">
              <!-- <el-input v-model="categories[nowRow].categoryName" autocomplete="off"></el-input> -->
              <el-input v-model="dialogForm.categoryName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="类型描述" :label-width="formLabelWidth">
              <!-- <el-input v-model="categories[nowRow].description" autocomplete="off"></el-input> -->
              <el-input v-model="dialogForm.description" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="图片" :label-width="formLabelWidth">
              <el-upload
                name="image"
                class="avatar-uploader"
                action="http://localhost:8888/uploads"
                :show-file-list="false"
                :on-success="handleAvatarSuccess"
                :before-upload="beforeAvatarUpload">
                <img v-if="dialogForm.image" :src="dialogForm.image" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="updateCategory()">确 定</el-button>
          </div>
        </el-dialog>

        <el-pagination
          small="false"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="innerPage.pageNumber"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="innerPage.pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="innerPage.totalCounts">
        </el-pagination>
    </div>
</template>

<script>
  import {getCategoryForAdmin} from '@/api/category'
  import {changeCategory} from '@/api/category'
  import {deleteCategory} from '@/api/category'
  import {deleteCategoryList} from '@/api/category'
  import {addCategory} from '@/api/category'
  import {getToken} from '@/request/token'

  export default {
    data() {
      return {
        dialogFormVisible: false,
        innerPage: {
          pageSize: 10,
          pageNumber: 1,
          totalCounts: 0,
          
        },
        categories:[],
        formInline:{},
        dialogForm:{},
        selectionList:[],
        dialogAddType: false,
        type:'category',
        id: -1,
        
        
      }
    },
    props: {
      offset: {
        type: Number,
        default: 100
      },
      page: {
        type: Object,
        default() {
          return {}
        }
      }
    },
    watch: {
      
      'page': {
        handler() {
          this.noData = false
          this.articles = []
          this.innerPage = this.page
          this.getCatrgories()
        },
        deep: true
      }
    },
    computed: {
      user() {
        let login = this.$store.state.account.length != 0
        let admin = this.$store.state.admin
        return {
          login, admin
        }
      }
    },
    created () {

      let token = getToken()
      if(token == null || this.user.login == false || this.user.admin < 1){
        //跳转到首页
        this.$router.push({path: '/'})
      }else{
        this.getCatrgories();
      }

    },
    methods: {

      openDialog(row, r){
        this.dialogFormVisible = true;
        if(r == -1){
          this.dialogForm = {};
          this.dialogAddType = true;
          return;
        }
        
        this.dialogForm.id = row.id
        this.dialogForm.categoryName = row.categoryName
        this.dialogForm.description = row.description
        this.dialogForm.image = row.avatar
      },

      load() {
        this.getCatrgories()
      },
      view(id) {
        this.$router.push({path: `/${this.type}/${id}`})
      },
      getCatrgories() {
        let that = this
        that.loading = true
        let token = getToken()
        getCategoryForAdmin(token, that.innerPage, that.formInline).then(data => {

          let newCategories = data.data.categoryList
          that.innerPage.pageSize = data.data.pageData.size
          that.innerPage.pageNumber = data.data.pageData.current
          that.innerPage.totalCounts = data.data.pageData.total
          that.categories = null
          if (newCategories && newCategories.length > 0) {
            that.categories = newCategories
          } else {
            that.noData = true
          }

        }).catch(error => {
          if (error !== 'error') {
            that.$message({type: 'error', message: '类型加载失败!', showClose: true})
          }
        }).finally(() => {
          that.loading = false
        })

      },
      handleSizeChange(val) {
        let that = this
        that.innerPage.pageSize = val
        this.getCatrgories()
      },
      handleCurrentChange(val) {
        let that = this
        that.innerPage.pageNumber = val
        this.getCatrgories()
      },
      
      updateCategory(){
        let that = this
        let token = getToken()
        if(this.dialogAddType){
          addCategory(token, that.dialogForm).then(data => {
            this.$message({
                message: '添加成功',
                type: 'success'
              });
            this.dialogFormVisible = false
          }).catch(error => {
              if (error !== 'error') {
                that.$message({type: 'error', message: '添加类型失败，请检查信息是否重复!', showClose: true})
              }
          }).finally(() => {
              that.getCatrgories();
          })
        }else{
          changeCategory(token, that.dialogForm).then(data => {
            this.$message({
                message: '修改成功',
                type: 'success'
              });
            this.dialogFormVisible = false
          }).catch(error => {
              if (error !== 'error') {
                that.$message({type: 'error', message: '类型修改失败，请检查信息是否重复!', showClose: true})
              }
          }).finally(() => {
              that.getCatrgories();
          })
        }
      },
      handleDelete(row) {
        let that = this
        let token = getToken()
        this.$confirm('此操作将永久删除该类型, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteCategory(token, row.id).then(data => {
            this.$message({
              message: '删除成功',
              type: 'success'
            });
          }).catch(error => {
            if (error !== 'error') {
              that.$message({type: 'error', message: '类型删除失败!', showClose: true})
            }
          }).finally(() => {
              that.getCatrgories();
          })
        }).catch(() => {
          that.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
      },
      onSubmit() {
        this.getCatrgories();
      },
      handleAvatarSuccess(res, file) {
        //this.dialogForm.image = URL.createObjectURL(file.raw);
        this.dialogForm.image = res.data
      },
      beforeAvatarUpload(file) {
        const isJPG = file.type === 'image/jpeg';
        const isLt2M = file.size / 1024 / 1024 < 2;

        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!');
        // }
        if (!isLt2M) {
          this.$message.error('上传头像图片大小不能超过 2MB!');
        }
        //return isJPG && isLt2M;
        return isLt2M;
      },
      deleteCategoryList(){
        let token = getToken()
        if(this.selectionList.length > 0){
          let arr = [];
          for (let i = 0; i < this.selectionList.length; i++) {
            arr[i] = this.selectionList[i].id;
          }
          let that = this
          this.$confirm('此操作将永久删除该类型, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            deleteCategoryList(token, arr).then(data => {
              this.$message({
                message: '删除成功',
                type: 'success'
              });
            }).catch(error => {
                if (error !== 'error') {
                  that.$message({type: 'error', message: '类型删除失败!', showClose: true})
                }
            }).finally(() => {
                that.getCatrgories();
            })
          }).catch(() => {
            that.$message({
              type: 'info',
              message: '已取消删除'
            });          
          });
          
        }else{
          this.$message({type: 'error', message: '选择内容为空!', showClose: true})
        }
      },
      handleSelectionChange(selection) {
        // 批量选中id
        this.selectionList = selection
      },
      
      
    }
  }
</script>

<style scoped>

  .avatar-uploader .el-upload {
    border: 1px dashed #888585;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
    

</style>